from app.storage.model import WarehouseRecord as WarehouseRecordTable
from app.storage.model import WarehouseFlow as WarehouseFlowTable
from exts import db
from common import constant




class Warehouse:
    def __init__(self, warehouse_id, user_id=None):
        self.id = warehouse_id
        self.user_id = user_id

    # # 采购
    # def update_record_by_purchase(self, sku_id, num, price):
    #     warehouse_record = WarehouseRecord(sku_id, self.id)
    #     warehouse_record.update_num(num)
    #     warehouse_record.update_cost_price(num, price)
    #
    # # 撤销采购
    # def update_record_by_revoke_purchase(self, sku_id, num, price):
    #     warehouse_record = WarehouseRecord(sku_id, self.id)
    #     warehouse_record.update_num(-num)
    #     warehouse_record.update_cost_price(-num, price)

    def create_flow(self, user_id, order_type, order_id, sku_id, num):
        wf = WarehouseFlowTable()
        wf.warehouse_id = self.id
        wf.sku_id = sku_id
        wf.num = num
        wf.creator_id = user_id
        wf.order_type = order_type
        wf.order_id = order_id
        db.session.add(wf)

    def remove_flow(self, order_id):
        wfs = WarehouseFlowTable.query.filter(order_id=order_id, warehouse_id=self.id)
        db.session.delete(wfs)

    # # 销售
    # def update_record_by_sale(self, sku_id, num):
    #     warehouse_record = WarehouseRecord(sku_id, self.id)
    #     warehouse_record.update_num(-num)
    #
    # # 撤销销售
    # def update_record_by_revoke_sale(self, sku_id, num):
    #     warehouse_record = WarehouseRecord(sku_id, self.id)
    #     warehouse_record.update_num(num)


class WarehouseRecord:
    def __init__(self, sku_id, warehouse_id):
        self.sku_id = sku_id
        self.warehouse_id = warehouse_id

        self.warehouse_record_table = self._get_table_db()

    def _get_table_db(self):
        warehouse_record_table = WarehouseRecordTable.query.filter_by(
            sku_id=self.sku_id, warehouse_id=self.warehouse_id).first()
        if not warehouse_record_table:
            warehouse_record_table = WarehouseRecordTable()
            warehouse_record_table.sku_id = self.sku_id
            warehouse_record_table.warehouse_id = self.warehouse_id
            db.session.add(warehouse_record_table)
        return warehouse_record_table

    def update_num(self, num):
        """修改"""
        self.warehouse_record_table.num = num

    def add_num(self, num):
        """增加"""
        self.warehouse_record_table.num += num

    def update_cost_price(self, change_num, price):
        """增加或减少 来修改库存成本单价
        采购： 增加
        撤销采购： 减少
        采购退货：减少
        撤销采购退货：增加
        销售：不变
        撤销销售：不变
        销售退货：不变
        撤销销售退货：不变
        """
        self.warehouse_record_table.cost_price = calculate_cost_price(
            self.warehouse_record_table.num, self.warehouse_record_table.cost_price,
            change_num, price
        )

